package com.pocket.demo.leetcode;

import java.util.*;

/**
 * 字母异位词分组
 *      https://leetcode.cn/problems/group-anagrams/description/?envType=study-plan-v2&envId=top-100-liked
 * @author zhaozhile
 */
public class _2_Array_GroupAnagrams {

    public List<List<String>> groupAnagrams(String[] strs) {
        if(strs == null || strs.length == 0){
            return new ArrayList<>();
        }
        if (strs.length == 1){
            return Arrays.asList(Arrays.asList(strs[0]));
        }
        Map<Integer, List<String>> groups = new HashMap<>();
        for (String str : strs) {
            int sum = 0;
            for(char c : str.toCharArray()){
                sum = sum + c;
            }
            if (groups.containsKey(sum)){
                groups.get(sum).add(str);
            } else {
                List<String> list = new ArrayList<>();
                list.add(str);
                groups.put(sum, list);
            }
        }
        return new ArrayList<>(groups.values());
    }

    public static void main(String[] args) {
        String[] strs = {"eat","tea","tan","ate","nat","bat"};
        System.out.println(new _2_Array_GroupAnagrams().groupAnagrams(strs));

    }


}
